<?php

class BookingController extends Controller {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('schedule', 'getEvents', 'resourceCalenderConfig', 'cancel', 'index', 'view', 'BookAppointment'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex() {
        $model = Service::model()->findAllByAttributes(array('isActive' => TRUE));
        $this->render('index', array('model' => $model));
    }

    public function actionSchedule($service) {
        $model = Service::model()->findAllByAttributes(array('id' => $service, 'isActive' => TRUE));
        $resources = $this->actionResourceForService($service);
        $this->render('book', array('model' => $model[0], 'resources' => $resources));
    }

    public function actionResourceForService($service) {
        return ServiceResource::getResourcces($service);
    }

    public function actionGetEvents() {
        $date = $_GET['start'];
        $resource_id = $_GET['resource'];
        $events = ResourceTiming::getAllEvents($date, $resource_id);
        $isemp = $this->hasRole(Yii::app()->user->id, 'employee');
        $_events = array();
        foreach ($events as $key => $value) {
            $event = array();
            $event['id'] = $value['id'];
            if ($isemp) {
                $entTitle = "";
                if (ResourceTiming::TYPE_SERVICE == $value['eventtype']) {
                    try {
                        $servicerequest = ServiceRequest::getServiceRequestOfEvent($value['id']);
                        if (isset($servicerequest)) {
                            $user = $servicerequest->user;
                            if (isset($user)) {
                                $entTitle.='Customer : ' . $servicerequest->user->profile->name;
                            } else {
                                $entTitle.='Unknown';
                            }
                            $entTitle.=', Service :' . $servicerequest->service->name;
                            if ($servicerequest->status == ServiceRequest::STATUS_DONE) {
                                $event['backgroundColor'] = '#999999';
                                $event['borderColor'] = '#999999';
                            } else {
                                $event['backgroundColor'] = '#399916';
                                $event['borderColor'] = '#399916';
                            }
                        }
                    } catch (Exception $ex) {
                        $entTitle.='Unknown Event';
                    }
                    $event['title'] = $entTitle;
                } else {
                    $event['title'] = $value['eventtype'].', '.$value['note'];
                    $event['backgroundColor'] = '#ffd597';
                    $event['borderColor'] = '#ffd597';
                }
            } else {
                $event['title'] = $value['eventtype'];
            }
            $event['start'] = $value['starttime'];
            $event['end'] = $value['endtime'];
            $event['allDay'] = $value['allDay'] == true ? true : false;
            array_push($_events, $event);
        }
        echo CJSON::encode($_events);
    }

    public function actionResourceCalenderConfig() {
        $date = $_GET['date'];
        $resource_id = $_GET['resource'];
        $service_id = $_GET['service'];
        $service = Service::model()->findAllByPk($service_id);
        if (!(isset($service) && isset($service[0]))) {
            throw new Exception('Invalid Service');
        }
        $cal_config = array();
        $cal_config['defaultView'] = 'agendaDay';
        $cal_config['minTime'] = Conf::getConf('DAY START');
        $cal_config['maxTime'] = Conf::getConf('DAY END');
        $cal_config['hiddenDays'] = array_map('intval', explode(',', Conf::getConf('WEEK ENDS')));
        $cal_config['slotMinutes'] = intval($service[0]->duration) > 5 ? intval($service[0]->duration) : 5;
        $cal_config['selectable'] = true;
        $cal_config ['selectHelper'] = true;
        $cal_config['editable'] = false;
        echo CJSON::encode($cal_config);
    }

    public function actionCancelAppointment() {
        $request_id = $_REQUEST['request_id'];
        if (!isset($request_id)) {
            echo 'Invalid Request';
            return;
        }
        $requests = ServiceRequest::model()->findAllByAttributes(array('id' => $request_id, 'userid' => Yii::app()->user->id));
        if (!isset($requests) || $requests . length < 1) {
            echo 'Unable to find Requst from Booking History';
            return;
        }
        $transation = Yii::app()->db->beginTransaction();
        try {
            ResourceTiming::model()->deleteByPk($requests[0]->eventid);
            ServiceRequest::model()->deleteByPk($requests[0]->id);
            $transation->commit();
        } catch (Exception $exc) {
            $transation->rollback();
            echo 'Unable to Delete Request' + $exc->getMessage();
        }
    }

    public function actionCancel() {
        $requestId = $_REQUEST['request'];
        $msg = null;
        if (isset($requestId)) {
            $request = ServiceRequest::model()->findByPk($requestId);
            if (isset($request) && $request->userid == Yii::app()->user->id) {
                try {
                    $event = ResourceTiming::model()->findByPk($request->eventid);
                    $transaction = Yii::app()->db->beginTransaction();
                    $request->delete();
                    $event->delete();
                    $transaction->commit();
                } catch (Exception $exc) {
                    $transaction->rollback();
                    $msg = 'Unable to delete Request : ' . $exc->getMessage();
                }
            } else {
                $msg = 'Your not authorized to do this';
            }
        }
        $this->redirect(array('dashboard/index', 'msg' => $msg));
    }

    public function actionBookAppointment() {
        $msg = "";
        $resource = $_REQUEST['resource'];
        $start = strtotime($_REQUEST['start']);
//        if($start.getTime()<date("Y-m-d H:i:s")){
//            echo 'Invalid Time.';
//            return;
//        }
        $end = $start;
        $service_id = $_REQUEST['service'];
        $service = Service::model()->findByPk($service_id);
        $end = $start + (60 * $service->duration);
        if (!isset(Yii::app()->user->id)) {
            throw new Exception("Unable to book Service : invalid user ");
        }
        $transation = Yii::app()->db->beginTransaction();
        try {


            if (!$this->checkAvailability($resource, $start, $end)) {
                throw new Exception("Slot not available");
            }
            $event = $this->createEvent($resource, $this->miliSecToFormated($start), $this->miliSecToFormated($end), $service->duration, false, ResourceTiming::TYPE_SERVICE);
            if (!$event) {
                throw new Exception("Unable to shedule Event..");
            }
            $this->createServicerequest($service_id, $event->id);
            $transation->commit();
            $msg.="Solt alloacted.. ";
            $status = "success";
        } catch (Exception $ex) {
            $status = "error";
            $msg.=$ex->getMessage();
            $transation->rollback();
        }
        echo CJSON::encode(array('status'=>$status,'message'=>$msg));
    }

    private function createServicerequest($service_id, $eventid) {
        $request = new ServiceRequest($scenario = 'insert');
        $request->service_id = $service_id;
        $request->requested_on = date("Y-m-d H:i:s");
        $request->eventid = $eventid;
        $request->userid = Yii::app()->user->id;
        $request->status = ServiceRequest::STATUS_SHEDULED;
        return $request->save();
    }

    private function createEvent($resource_id, $start, $end, $duration, $allDay, $eventType) {
        $event = new ResourceTiming;
        $event->resource = intval($resource_id);
        $event->eventOn = $start;
        $event->starttime = $start;
        $event->endtime = $end;
        $event->duration = intval($duration);
        $event->allDay = $allDay;
        $event->eventtype = $eventType;
        if ($event->save()) {
            return $event;
        }
        return FALSE;
    }

    private function miliSecToFormated($date) {
        return date('Y-m-d H:i:s', $date);
    }

    private function checkAvailability($resource, $start, $end) {
        return ResourceTiming::checkAvailability(date('Y-m-d', $start), date('Y-m-d H:i:s', $start), date('Y-m-d H:i:s', $end), $resource);
    }

    public function hasRole($userid, $hasrole) {
        $roles = Rights::getAssignedRoles(Yii::app()->user->Id);
        foreach ($roles as $role) {
            if ($role->name == $hasrole) {
                return true;
            }
        }
        return FALSE;
    }

    // Uncomment the following methods and override them if needed
    /*
      public function filters()
      {
      // return the filter configuration for this controller, e.g.:
      return array(
      'inlineFilterName',
      array(
      'class'=>'path.to.FilterClass',
      'propertyName'=>'propertyValue',
      ),
      );
      }

      public function actions()
      {
      // return external action classes, e.g.:
      return array(
      'action1'=>'path.to.ActionClass',
      'action2'=>array(
      'class'=>'path.to.AnotherActionClass',
      'propertyName'=>'propertyValue',
      ),
      );
      }
     */
}
